﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using zhangkong.ViewModels;

namespace zhangkong
{
    public partial class CoursePageSettings : PhoneApplicationPage
    {
        private static BackgroundImageList viewModel = null;
        public static BackgroundImageList ViewModel
        {
            get
            {
                if (viewModel != null)//如果已经初始化那么就直接返回
                    return viewModel;
                string dataFromAppSetting;
                if (IsolatedStorageSettings.ApplicationSettings.TryGetValue(App.IsoImageList, out dataFromAppSetting))//尝试从IsoStore中获取信息
                {
                    viewModel = JsonConvert.DeserializeObject<BackgroundImageList>(dataFromAppSetting);
                    return viewModel;
                }
                viewModel = new BackgroundImageList();//如果没有在IsoStore中获取到信息，那么直接载入本地的数据——也就是应用第一次开启时会被执行
                viewModel.LoadData();//应用第一次开启时会被执行
                return viewModel;

            }
        }

        public bool isLoading = true;//解决因为使用了ListPicker空间而导致的闪退问题

        PeriodicTask periodicTask;

        string periodicTaskName = "PeriodicAgent";

        public CoursePageSettings()
        {
            InitializeComponent();

            DataContext = ViewModel;
        }



        #region ToggleSwitch Checked && UnChecked

        private void DynamicTile_Checked(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings.ApplicationSettings["DynamicTile"] = true;
            App.DynamicTile = true;

            StartPeriodicAgent();

        }

        private void DynamicTile_UnChecked(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings.ApplicationSettings["DynamicTile"] = false;
            App.DynamicTile = false;

            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

        }

        #endregion


        #region Background Schedule Agent
        private void StartPeriodicAgent()
        {
            if (App.DynamicTile == false)
                return;

            // Obtain a reference to the period task, if one exists
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "This demonstrates a periodic task.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
            ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(10));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.

                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
        }


        private void RemoveAgent(string name)
        {

            try
            {
                ScheduledActionService.Remove(name);
            }
            catch (Exception)
            {
            }
        }

        #endregion

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            TileToggleSwitch.IsChecked = App.DynamicTile;
            LoadBackgroundImage();
            MaximumCoursesListPicker.SelectedIndex = App.MaximumCourseNumber - 11;
        }

        private void LoadBackgroundImage()
        {
            try
            {
                BitmapImage img = new BitmapImage();
                string filePath = App.BackgroundImageUri;
                using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (iso.FileExists(filePath))
                    {
                        using (var source = iso.OpenFile(filePath, FileMode.Open, FileAccess.Read))
                        {
                            img.SetSource(source);
                        }
                        ImageBrush imgBrush = new ImageBrush();
                        imgBrush.ImageSource = img;
                        LayoutRoot.Background = imgBrush;
                    }
                    else
                    {
                        MessageBox.Show("亲，没能找到背景图片！请卸载后重新安装应用！");
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\nError In\nCoursePgae.xaml\n反馈有奖");
            }

        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            var data = JsonConvert.SerializeObject(viewModel);
            IsolatedStorageSettings.ApplicationSettings[App.IsoImageList] = data;

            IsolatedStorageSettings.ApplicationSettings.Save();//保存信息
        }

        private void ChangeBackgroundUri_SelectionChangd(object sender, SelectionChangedEventArgs e)
        {
            LongListSelector selector = sender as LongListSelector;
            if (selector == null)
                return;
            BackgroundImage img = (BackgroundImage)selector.SelectedItem;
            App.BackgroundImageUri = img.FilePath;
            IsolatedStorageSettings.ApplicationSettings["BackgroundImageUri"] = App.BackgroundImageUri;
            LoadBackgroundImage();
        }

        private void ReparseData_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (isLoading)
            {
                isLoading = false;
                return;
            }

            if (App.IsCourseImported == false) 
                return;

            ListPicker listPicker = sender as ListPicker;
            if (listPicker == null) 
                return;

            if (listPicker.SelectedIndex == App.MaximumCourseNumber - 11)
                return;
            else
            {
                App.MaximumCourseNumber = 11 + listPicker.SelectedIndex;
                IsolatedStorageSettings.ApplicationSettings["MaximumCourseNumber"] = App.MaximumCourseNumber;
                ProgressBar.Visibility = Visibility.Visible;
                MaximumCoursesListPicker.IsEnabled = false;
                Dispatcher.BeginInvoke(delegate
                {
                    ReparseDataFromIsoStore();
                });
            }
        }

        private void ReparseDataFromIsoStore()
        {
            DateTime startTime = new DateTime(2014, 9, 1);
            string[] startTimeofCourse = new string[]
                        {
                            "8:10:0", "9:0:0", "10:15:0", "11:05:0", "12:40:0", "14:30", "15:20:0", "16:15:0", "17:05:0",
                            "19:10:0", "20:0:0", "20:50:0"
                        };

            string[] endTimeofCourse = new[]
                        {
                            "8:55:0", "9:45:0", "11:0:0", "11:50:0", "14:0:0", "15:15:0", "16:05:0", "17:0:0", "17:50",
                            "19:55:0", "20:45:0", "21:35:0"
                        };


            int termLength;
            if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue("TermLength", out termLength))
            {
                termLength = 22;
            }

            string[] allCourseData = new string[termLength];

            for (int i = 0; i < termLength; i++)
            {
                allCourseData[i] = Convert.ToString(IsolatedStorageSettings.ApplicationSettings["Week" + i.ToString()]);
            }

            for (int k = 0; k < allCourseData.Length; k++)
            {
                string weeklyCourseData = allCourseData[k];
                if (weeklyCourseData == "")
                    continue;

                JObject jsonData = JObject.Parse(weeklyCourseData);

                WeeklyCourses weekly = new WeeklyCourses();
                for (int i = 0; i < 7; i++)
                {
                    DailyCourses daily = new DailyCourses();

                    for (int j = 0; j < 12; )
                    {
                        bool whetherIgnore = false;//是否跳过中午那节课，用于课程结束时间的判断
                        Course course = new Course();

                        course.CourseName = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["coursename"].ToString();
                        if (course.CourseName == "教研" || course.CourseName == "中秋节" ||
                            course.CourseName == "国庆节" || course.CourseName == "报到注册" ||
                            course.CourseName == "考试周" || course.CourseName == "元旦节")
                            course.CourseName = "";

                        course.Classroom = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["classroom"].ToString();
                        course.CourseType = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["lilun"].ToString();
                        course.Credits = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["xuefen"].ToString();
                        course.ClassHours = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["xueshi"].ToString();
                        course.TeacherName = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["teacher"].ToString();
                        course.StartTime =
                            DateTime.Parse(startTime.Year + "/" + startTime.Month + "/" + startTime.Day +
                                           " " + startTimeofCourse[j]);
                        int length = 1;
                        //循环查询下一节课是否和本节相同
                        while (j + length < 12 && course.CourseName ==
                               jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][
                                   (j + 1 + length).ToString()]["coursename"].ToString()
                                   && course.Classroom == jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][
                                   (j + 1 + length).ToString()]["classroom"].ToString()
                                   )
                        {
                            length++;
                            if (length + j == 4 && App.MaximumCourseNumber == 11) //跳过中午那节课
                            {
                                j++;
                                whetherIgnore = true;
                            }

                        }

                        j += length;
                        if (whetherIgnore)
                            course.EndTime =
                                DateTime.Parse(startTime.Year + "/" + startTime.Month + "/" + startTime.Day +
                                               " " + endTimeofCourse[j - 2]);
                        else
                            course.EndTime =
                                DateTime.Parse(startTime.Year + "/" + startTime.Month + "/" + startTime.Day +
                                               " " + endTimeofCourse[j - 1]);

                        course.Length = length;
                        daily.DailyCoursesCollection.Add(course);
                    }
                    startTime = startTime.AddDays(1);
                    weekly.WeeklyCoursesCollention.Add(daily);
                }
                var dataofWeeks = JsonConvert.SerializeObject(weekly);
                IsolatedStorageSettings.ApplicationSettings["ParsedWeek" + k.ToString()] = dataofWeeks;
            }
            IsolatedStorageSettings.ApplicationSettings.Save();
            ProgressBar.Visibility = Visibility.Collapsed;
            MaximumCoursesListPicker.IsEnabled = true;
        }

        private void ChoosePictureFromAlbum_Click(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask chooserTask = new PhotoChooserTask();
            chooserTask.PixelHeight = 800;
            chooserTask.PixelWidth = 480;
            chooserTask.ShowCamera = true;
            chooserTask.Completed += chooserTask_Completed;
            chooserTask.Show();
        }

        void chooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage img = new BitmapImage();
                ImageBrush imgBrush = new ImageBrush();
                try
                {
                    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!storage.DirectoryExists("BackgroundImage"))
                            storage.CreateDirectory("BackgroundImage");

                        if (storage.FileExists("BackgroundImage/4.jpg")) 
                            storage.DeleteFile("BackgroundImage/4.jpg");

                        using (IsolatedStorageFileStream stream = storage.CreateFile("BackgroundImage/4.jpg"))
                        {
                            int chunkSize = 2048;
                            byte[] bytes = new byte[chunkSize];
                            int byteCount;

                            while ((byteCount = e.ChosenPhoto.Read(bytes, 0, chunkSize)) > 0)
                            {
                                stream.Write(bytes, 0, byteCount);
                            }
                        }

                    }
                    App.BackgroundImageUri = "BackgroundImage/4.jpg";
                    IsolatedStorageSettings.ApplicationSettings["BackgroundImageUri"] = App.BackgroundImageUri;
                    IsolatedStorageSettings.ApplicationSettings.Save();
                    LoadBackgroundImage();
                }
                catch (Exception)
                {
                    MessageBox.Show("获取图片失败");
                }





            }







        }

    }

    public class PathToImage : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                BitmapImage img = new BitmapImage();
                string filePath = (string)value;
                using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (iso.FileExists(filePath))
                    {
                        using (IsolatedStorageFileStream stream = iso.OpenFile(filePath, FileMode.Open, FileAccess.Read))
                        {
                            img.SetSource(stream);
                        }
                    }
                    else
                    {
                        img = null;
                    }
                }

                return img;
            }
            catch (ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
}